<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button :disabled="addButtonDisabled"  @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <div class="configSettingBtns" v-show="selectedRowKeys.length===1">
        <a-button type="primary" icon="car" @click="configSetting(0,selectedRowKeys[0])">出入口信息配置</a-button>
        <a-button type="primary" icon="scan" @click="configSetting(1,selectedRowKeys[0])">识别参数信息配置</a-button>
        <a-button type="primary" icon="money-collect" @click="configSetting(2,selectedRowKeys[0])">计费规则信息配置</a-button>
        <a-button type="primary" icon="right-square" @click="configSetting(3,selectedRowKeys[0])">通行设置</a-button>
        <a-button type="primary" icon="scan" @click="configSetting(4,selectedRowKeys[0])">月卡配置</a-button>
      </div>
    </div>
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="configSetting(0,'',record)">信息配置</a>
          <a-divider type="vertical"/>
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical"/>
        </span>

      </a-table>
    </div>

    <parkInfo-modal ref="modalForm" @ok="modalFormOk"></parkInfo-modal>
    <ConfigSettingModal ref="configSettingModal"></ConfigSettingModal>

  </a-card>
</template>

<script>
import ParkInfoModal from './modules/ParkInfoModal'
import ConfigSettingModal from '../ConfigSettingModal'
import {
  JeecgListMixin
} from '@/mixins/JeecgListMixin'
import {
  deleteAction,
  httpAction,
  getAction,
  downFile
} from '@/api/manage'
import {
  filterObj
} from '@/utils/util';


export default {
  name: "ParkInfoList",
  mixins: [JeecgListMixin],
  components: {
    ParkInfoModal,
    ConfigSettingModal,
  },
  data() {
    return {
      description: '停车场信息管理页面',
      addButtonDisabled:true,
      columns: [{
        title: '序号',
        dataIndex: '',
        key: 'rowIndex',
        width: 60,
        align: "center",
        customRender: function (t, r, index) {
          return parseInt(index) + 1;
        }
      },
        {
          title: '停车场编号',
          align: "center",
          dataIndex: 'parkCode'
        },
        {
          title: '停车场名称',
          align: "center",
          dataIndex: 'parkName'
        },
        {
          title: '停车场位置',
          align: "center",
          dataIndex: 'parkPosition'
        },

        {
          title: '停车场状态',
          align: "center",
          dataIndex: 'parkStatus',
          // eslint-disable-next-line no-unused-vars
          customRender: function (t, r, index) {
            if (t === '1'||t===1) {
              return  '正常';
            } else if (r === '2'||t===2) {
              return '停止';
            }
          }
        },
        {
          title: '商户名称',
          align: "center",
          dataIndex: 'merchantName'
        },
        {
          title: '发票状态',
          align: "center",
          dataIndex: 'invoiceType',
          // eslint-disable-next-line no-unused-vars
          customRender: function (t, r, index) {
            if (t === '0'||t===0) {
              return  '未开通';
            } else if (t === '1'||t===1) {
              return '国票';
            } else if (t === '2'||t===2) {
              return  '百旺';
            }
          }
        },
        {
          title: '创建时间',
          align: "center",
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          scopedSlots: {
            customRender: 'action'
          },
        }
      ],
      url: {
        list: "/parking/parkInfo/list",
        delete: "/parking/parkInfo/delete",
        deleteBatch: "/parking/parkInfo/deleteBatch",
        exportXlsUrl: "parking/parkInfo/exportXls",
        importExcelUrl: "parking/parkInfo/importExcel",
        edit: "/jddhlw/parkingQR/parkInfoQRcode",
        sync: "/parking/parkInfo/parkSyncConfigOption"

      },
      queryParam: {
        "opTime_begin": "",
        "opTime_end": "",
        "type": "-1",
      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {
    this.keyupEnter()
  },
  methods: {


    configSetting(index, selectedKey, record) {
      if (selectedKey) {
        record = this.dataSource.find(function (item) {
          return item.id === selectedKey;
        });
      }
      this.$refs.configSettingModal.open(index, record);
    },
    handleSync(record){
      let Params={}
      Params.id = record.id
      Params.parkCode = record.parkCode
      httpAction(this.url.sync,Params,'post').then((res)=>{
        if(res.success)
        {
          this.$message.success(res.message)
        }
        else {
          if(res.result)
          {
            this.$message.warning(res.message+':'+res.result)
          }
          else {
            this.$message.warning(res.message)
          }
        }
      })
    },
    handleExportXls(fileName) {

      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;
      let opDesc = this.queryParam.opDesc;
      let dayTime = startTime;
      if (startTime === "") {
        this.$message.error("请选择导出开始日期");
        return
      }
      if (endTime === "") {
        this.$message.error("请选择导出结束日期");
        return
      }
      if (startTime === "" && endTime !== "") {
        this.$message.error("请选择开始时间");
        return
      }
      if (startTime !== "" && endTime === "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.queryParam.dayTime = dayTime;
      fileName = dayTime + fileName;
      let param = {
        ...this.queryParam
      };
      if (this.queryParam.opTime_begin !== "" && this.queryParam.opTime_end !== "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    onChangeStartTime(date, dateString) {
      this.queryParam.opTime_begin = dateString;
    },
    onChangeEndTime(date, dateString) {
      this.queryParam.opTime_end = dateString;
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      let params = this.getQueryParams(); //查询条件
      if (this.parkCode === "") {
        params.parkCode = null;
      }
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records;
          if(this.dataSource.length>0)
          {
            this.addButtonDisabled = true;
          }
          else {
            this.addButtonDisabled = false
          }
          this.ipagination.total = res.result.total;
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false;
      })
    },

    searchQuery() {
      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;
      if (startTime !== "" && endTime !== "") {
        if (startTime > endTime) {
          this.$message.error("开始时间不能大于结束时间");
          return
        }
      }
      if (startTime === "" && endTime !== "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime !== "" && endTime === "") {
        this.$message.error("请选择结束时间");
        return
      }
      this.loadData(1);
    },

    getQueryParams() {
      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      param.parkCode = this.parkCode;
      if (this.queryParam.opTime_begin !== "" && this.queryParam.opTime_end !== "") {
        param.startTime = this.queryParam.opTime_begin + " 00:00:00";
        param.endTime = this.queryParam.opTime_end + " 23:59:59";
      }
      return filterObj(param);
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectionRows.length; a++) {
          ids += this.selectionRows[a].invateuserdetailId + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            deleteAction(that.url.deleteBatch, {
              ids: ids
            }).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            });
          }
        });
      }
    },
    handleDelete: function (invateuserdetailId) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {
        invateuserdetailId: invateuserdetailId
      }).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },
    handleQr: function (record) {
      const that = this;
      let httpurl = '';
      let method = '';
      httpurl += this.url.edit;
      method = 'post';
      downFile(this.url.edit, record).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), 'qrcode.png')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', record.parkName + "场内码" + ".png")
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      }).finally(() => {
      })
    },
    keyupEnter() {
      document.onkeydown = e => {
        let body = document.getElementsByTagName('body')[0]
        if (e.keyCode === 13) {
          this.loadData(1);
        }
      }
    },
    onSelectChange: function (selectedRowKeys, selectionRows) {
      if (selectedRowKeys.length > 2) {
        this.selectedRowKeys = [selectedRowKeys[0]]
        this.selectionRows = [selectionRows[0]]
      } else {
        if (selectedRowKeys.length <= 1) {
          this.selectedRowKeys = selectedRowKeys
          this.selectionRows = selectionRows
        } else {
          this.selectedRowKeys = [selectedRowKeys.pop()]
          this.selectionRows = [selectionRows.pop()]
        }
      }
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';

.table-operator {
  display: flex;
}
</style>
